package com.sunny.l46;

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        return bfs(root);
    }

    public ArrayList<ArrayList<Integer>> bfs(TreeNode root){
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if(null == root)
            return res;
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        int size1 = 1;
        int size2 = 0;
        int tag = 1;
        stack1.push(root);
        ArrayList<Integer> tmpRes = new ArrayList<>();
        while ((1 == tag && !stack1.isEmpty()) || (2 == tag && !stack2.isEmpty())){
            if(1 == tag){
                TreeNode tmp = stack1.pop();
                tmpRes.add(tmp.val);
                size1--;
                if(null != tmp.left){
                    stack2.push(tmp.left);
                    size2++;
                }
                if(null != tmp.right){
                    stack2.push(tmp.right);
                    size2++;
                }
                if(0 == size1){
                    res.add(tmpRes);
                    tmpRes = new ArrayList<>();
                    tag = 2;
                }
            }else if(2 == tag){
                TreeNode tmp = stack2.pop();
                tmpRes.add(tmp.val);
                size2--;
                if(null != tmp.right){
                    stack1.push(tmp.right);
                    size1++;
                }
                if(null != tmp.left){
                    stack1.push(tmp.left);
                    size1++;
                }
                if(0 == size2){
                    res.add(tmpRes);
                    tmpRes = new ArrayList<>();
                    tag = 1;
                }
            }
        }
        return res;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}